package com.lin.benchmade.utils;

import java.util.HashMap;
import java.util.Map;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinYinUtils {

	private static HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
	private static Map<Character, String> pinyinConvertorCache = new HashMap<Character, String>(1024);

	static {
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
	}

	/**
	 */
	public static String char2Spell(char charValue) {
		String result = pinyinConvertorCache.get(charValue);
		if (result != null) {
			return result;
		}
		// 如果缓冲中没有在进行处理，缓冲数据都是判断后的数据，所以默认缓冲中的数据都认为是正确的
		if (PinYinUtils.isChineseChar(charValue)) {
			try {
				String[] yin = PinyinHelper.toHanyuPinyinStringArray(charValue, defaultFormat);
				if (yin != null) {
					result = yin[0];
					pinyinConvertorCache.put(charValue, result);
				}
			} catch (BadHanyuPinyinOutputFormatCombination e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static boolean isChineseChar(char charValue) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(charValue);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) {
			return true;
		}
		return false;
	}

}
